package com.yj.suncity.publish;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.yj.suncity.R;
import com.yj.suncity.constant.URLCon;
import com.yj.suncity.utis.DialogUtils;
import com.yj.suncity.utis.HttpUtil;
import com.yj.suncity.utis.ProgressUtil;
import com.yj.suncity.utis.TimePickUtils;
import com.yj.suncity.utis.ToastUtil;
import com.yj.suncity.utis.UploadUtil;
import com.yj.suncity.utis.Utils;
import com.yj.suncity.utis.DialogUtils.ItemCall;
import com.yj.suncity.utis.TimePickUtils.OnTimeDateSelectListener;
import com.yj.suncity.utis.UploadUtil.OnUploadProcessListener;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class PublishHuodongActivity extends Activity implements OnClickListener {
	private static final int FAIL = 1;
	private static final int SUCCESS = 2;
	private static final int IO_EXCEPTION = 3;
	private static final int JSON_EXCEPTION = 4;
	private Context context;
	private String userId;
	private TextView mTxt_activity_start_time, mTxt_activity_end_time,
			mTxt_publish_start_time, mTxt_publish_end_time;
	private EditText mEdt_activity_title, mEdt_activity_content,
			mEdt_activity_address;
	private String picPath;// 拍照后保存图片的路径
	private ProgressUtil progressUtil;
	private ArrayList<String> uploadPaths = new ArrayList<String>();
	private List<NameValuePair> pairs = new ArrayList<NameValuePair>();
	private Button mBtn_add_img;
	private RelativeLayout mLay_rela_img;
	private TextView mTxt_img_num;
	private ImageView mImg_all_logo;
	private ImageLoader imageLoader = ImageLoader.getInstance();
	private DisplayImageOptions options;

	Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case FAIL:
				progressUtil.ShowProgress(context, false, false, "正在上传......");
				ToastUtil.ShowToast(context, ""+(String)msg.obj);
				break;
			case SUCCESS:
				progressUtil.ShowProgress(context, false, false, "正在上传......");
				ToastUtil.ShowToast(context, "上传成功！");
				PublishHuodongActivity.this.finish();
				break;
			case IO_EXCEPTION:
				progressUtil.ShowProgress(context, false, false, "正在上传......");
				ToastUtil.ShowToast(context, "网络异常！");
				break;
			case JSON_EXCEPTION:
				progressUtil.ShowProgress(context, false, false, "正在上传......");
				ToastUtil.ShowToast(context, "数据解析异常！");
				break;
			default:
				break;
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_publish_activity);
		context = this;
		userId = getIntent().getStringExtra("userid");
		options = new DisplayImageOptions.Builder()
				.showStubImage(R.drawable.android_layout_detail)
				.showImageForEmptyUri(R.drawable.android_layout_detail)
				.showImageOnFail(R.drawable.android_layout_detail)
				.cacheInMemory(true).cacheOnDisc(true)
				// .displayer(new RoundedBitmapDisplayer(10))// 设置成圆角图片
				.bitmapConfig(Bitmap.Config.RGB_565) // 设置图片的解码类型
				.build();
		findView();
	}

	private void findView() {
		findViewById(R.id.btnHeadBack).setOnClickListener(this);
		findViewById(R.id.btn_ok).setOnClickListener(this);

		mBtn_add_img = (Button) findViewById(R.id.btn_add_img);
		mBtn_add_img.setOnClickListener(this);
		mLay_rela_img = (RelativeLayout) findViewById(R.id.lay_rela_img);
		mTxt_img_num = (TextView) findViewById(R.id.txt_img_num);
		mImg_all_logo = (ImageView) findViewById(R.id.img_all_logo);
		mImg_all_logo.setOnClickListener(this);

		mTxt_activity_start_time = (TextView) findViewById(R.id.txt_activity_start_time);
		mTxt_activity_start_time.setOnClickListener(this);
		mTxt_activity_end_time = (TextView) findViewById(R.id.txt_activity_end_time);
		mTxt_activity_end_time.setOnClickListener(this);

		mTxt_publish_start_time = (TextView) findViewById(R.id.txt_publish_start_time);
		mTxt_publish_start_time.setOnClickListener(this);
		mTxt_publish_end_time = (TextView) findViewById(R.id.txt_publish_end_time);
		mTxt_publish_end_time.setOnClickListener(this);

		mEdt_activity_title = (EditText) findViewById(R.id.edt_activity_title);
		mEdt_activity_content = (EditText) findViewById(R.id.edt_activity_detail);
		mEdt_activity_address = (EditText) findViewById(R.id.edt_activity_address);

	}

	/**
	 * 重置图片布局
	 */
	private void setAdapter() {
		// mPublish_img_gallery.setAdapter(new PublishGalleryAdapter(context,
		// uploadPaths));
		// if (uploadPaths.size() > 0) {
		// mPublish_img_gallery.setSelection(1);
		// }
		if (uploadPaths.size() == 9) {
			mBtn_add_img.setVisibility(View.GONE);
			mLay_rela_img.setVisibility(View.VISIBLE);
			mTxt_img_num.setText(String.valueOf(uploadPaths.size()));
			imageLoader.displayImage("file://" + uploadPaths.get(0),
					mImg_all_logo, options);
		} else if (uploadPaths.size() < 9 && uploadPaths.size() > 0) {
			mBtn_add_img.setVisibility(View.VISIBLE);
			mLay_rela_img.setVisibility(View.VISIBLE);
			mTxt_img_num.setText(String.valueOf(uploadPaths.size()));
			imageLoader.displayImage("file://" + uploadPaths.get(0),
					mImg_all_logo, options);
		} else {
			mBtn_add_img.setVisibility(View.VISIBLE);
			mLay_rela_img.setVisibility(View.GONE);
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btnHeadBack:
			this.finish();
			break;
		case R.id.txt_activity_start_time:
			TimePickUtils.dateSelect(context, new OnTimeDateSelectListener() {
				@Override
				public void onDateListener(String time) {
					mTxt_activity_start_time.setText(time);
				}
			});
			break;
		case R.id.txt_activity_end_time:
			TimePickUtils.dateSelect(context, new OnTimeDateSelectListener() {
				@Override
				public void onDateListener(String time) {
					mTxt_activity_end_time.setText(time);
				}
			});
			break;
		case R.id.txt_publish_start_time:
			TimePickUtils.dateSelect(context, new OnTimeDateSelectListener() {
				@Override
				public void onDateListener(String time) {
					mTxt_publish_start_time.setText(time);
				}
			});
			break;
		case R.id.txt_publish_end_time:
			TimePickUtils.dateSelect(context, new OnTimeDateSelectListener() {
				@Override
				public void onDateListener(String time) {
					mTxt_publish_end_time.setText(time);
				}
			});
			break;
		case R.id.btn_add_img:// 添加图片按钮
			popView();
			break;
		case R.id.img_all_logo:// 点击图片查看
			Bundle bundle = new Bundle();
			bundle.putStringArrayList("paths", uploadPaths);
			bundle.putInt("posi", 0);
			Intent intent = new Intent(context, SelectPicShowActivity.class);
			intent.putExtras(bundle);
			startActivityForResult(intent, 103);
			break;
		case R.id.btn_ok:
			String activityTheme = mEdt_activity_title.getText().toString()
					.trim();
			String activityAddress = mEdt_activity_address.getText().toString()
					.trim();
			String activityContent = mEdt_activity_content.getText().toString()
					.trim();
			String activityStartTime = mTxt_activity_start_time.getText()
					.toString().trim();
			String activityEndTime = mTxt_activity_end_time.getText()
					.toString().trim();
			activityStartTime = Utils.TimeToTimestamp(activityStartTime);
			activityEndTime = Utils.TimeToTimestamp(activityEndTime);

			String publishStartTime = mTxt_publish_start_time.getText()
					.toString().trim();
			String publishEndTime = mTxt_publish_end_time.getText().toString()
					.trim();
			publishStartTime = Utils.TimeToTimestamp(publishStartTime);
			publishEndTime = Utils.TimeToTimestamp(publishEndTime);

			if (activityTheme.equals("")) {
				ToastUtil.ShowToast(context, "请输入活动主题！");
				return;
			}
			if (activityStartTime.equals("")) {
				ToastUtil.ShowToast(context, "请选择活动开始日期！");
				return;
			}
			if (activityEndTime.equals("")) {
				ToastUtil.ShowToast(context, "请选择活动截止日期！");
				return;
			}

			if (publishStartTime.equals("")) {
				ToastUtil.ShowToast(context, "请选择发布开始日期！");
				return;
			}
			if (publishEndTime.equals("")) {
				ToastUtil.ShowToast(context, "请选择发布截止日期！");
				return;
			}

			if (activityAddress.equals("")) {
				ToastUtil.ShowToast(context, "请输入活动地址！");
				return;
			}

			if (activityContent.equals("")) {
				ToastUtil.ShowToast(context, "请输入活动内容！");
				return;
			}
			if (uploadPaths.size() <= 0) {
				ToastUtil.ShowToast(context, "请选择图片！");
				return;
			}

			uploadImg(activityTheme, activityContent, activityAddress,
					activityStartTime, activityEndTime, publishStartTime,
					publishEndTime);

			break;
		default:
			break;
		}
	}

	private StringBuffer stringBuffer = new StringBuffer();

	private void uploadImg(final String activityTheme,
			final String activityContent, final String activityAddress,
			final String activityStartTime, final String activityEndTime,
			final String publishStartTime, final String publishEndTime) {
		Map<String, String> param = new HashMap<String, String>();
		param.put("action", "uploads");
		UploadUtil uploadUtil = new UploadUtil();
		progressUtil = new ProgressUtil();
		progressUtil.ShowProgress(context, true, false, "正在上传......");
		uploadUtil.uploadFile(context, uploadPaths, "txtimg", URLCon.图片上传,
				param, new OnUploadProcessListener() {
					@Override
					public void UploadResule(String result) {
						Log.d("", "result===" + result);
						try {
							JSONObject jsonObject = new JSONObject(result);
							if (jsonObject.optString("success").equals("1")) {
								JSONArray array = jsonObject
										.optJSONArray("data");
								stringBuffer.delete(0, stringBuffer.length());
								for (int i = 0; i < array.length(); i++) {
									String url = array.optJSONObject(i)
											.optString("url");
									stringBuffer.append(url + ",");
								}
								stringBuffer.deleteCharAt(stringBuffer.length() - 1);
								publishProduct(activityTheme, activityContent,
										activityAddress, activityStartTime,
										activityEndTime, publishStartTime,
										publishEndTime);
							} else {
								Message message = new Message();
								message.what = FAIL;
								message.obj=jsonObject.optString("msg");
								handler.sendMessage(message);
							}
						} catch (JSONException e) {
							Message message = new Message();
							message.what = JSON_EXCEPTION;
							handler.sendMessage(message);
							e.printStackTrace();
						}
					}
				});
	}

	private void publishProduct(String activityTheme, String activityContent,
			String activityAddress, String activityStartTime,
			String activityEndTime, String publishStartTime,
			String publishEndTime) {
		pairs.clear();
		final String path = URLCon.活动;
		pairs.add(new BasicNameValuePair("action", "publishactivity"));
		pairs.add(new BasicNameValuePair("userid", userId));
		pairs.add(new BasicNameValuePair("activity_theme", activityTheme));
		pairs.add(new BasicNameValuePair("activity_content", activityContent));
		pairs.add(new BasicNameValuePair("activity_address", activityAddress));
		pairs.add(new BasicNameValuePair("release_datetime", publishStartTime));
		pairs.add(new BasicNameValuePair("release_endtime", publishEndTime));
		pairs.add(new BasicNameValuePair("activity_startdatetime", activityStartTime));
		pairs.add(new BasicNameValuePair("activity_enddatetime", activityEndTime));
		pairs.add(new BasicNameValuePair("txtimg", stringBuffer.toString()));
		

		Thread thread = new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					String json = HttpUtil.HttpClientdoPost(path, pairs);
					JSONObject jsonObject = new JSONObject(json);
					Message message = new Message();
					if (jsonObject.optString("success").equals("1")) {
						message.what = SUCCESS;
					} else {
						message.what = FAIL;
						message.obj=jsonObject.optString("msg");
					}
					handler.sendMessage(message);

				} catch (IOException e) {
					Message message = new Message();
					message.what = IO_EXCEPTION;
					handler.sendMessage(message);
					e.printStackTrace();
				} catch (JSONException e) {
					Message message = new Message();
					message.what = JSON_EXCEPTION;
					handler.sendMessage(message);
					e.printStackTrace();
				}
			}
		});
		thread.start();
		thread = null;
	}

	private void popView() {
		DialogUtils dialogUtils = DialogUtils.getInstance();
		dialogUtils.SelectPicDialog(context, new ItemCall() {
			@Override
			public void onIndexCall(int index) {
				if (index == 0) {// 拍照
					startPaizhao();
				} else if (index == 1) {// 相册
					startXiangce();
				}
			}
		});
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// upImgPath.clear();
		// 拍照后返回的数据
		if (requestCode == 110) {
			uploadPaths.add(picPath);
			// imaLayout.removeAllViews();
			if (uploadPaths.size() > 9) {
				uploadPaths.remove(picPath);
				ToastUtil.ShowToast(context, "您最多可以选择9张图片！");
				return;
			}
			setAdapter();
		}

		// 查看选择的图片后并且将图片全部删除后返回的数据
		if (requestCode == 103 && resultCode == 104) {
			uploadPaths.clear();
			// imaLayout.removeAllViews();
			// mBtnAddPic.setVisibility(View.VISIBLE);
			setAdapter();
		}

		// 查看选择的图片后返回的数据
		if (requestCode == 103 && resultCode == 103) {
			List<String> paths = data.getStringArrayListExtra("picPaths");
			if (paths != null && paths.size() > 0) {
				// imaLayout.removeAllViews();
				uploadPaths.clear();
				uploadPaths.addAll(paths);
				// 利用HashSet过滤掉一样的路径
				HashSet<String> set = new HashSet<String>(uploadPaths);
				uploadPaths.clear();
				uploadPaths.addAll(set);

				setAdapter();
			}
		}

		// 选择本地图库图片后返回的数据
		if (requestCode == 103 && resultCode == 105) {
			List<String> paths = data.getStringArrayListExtra("picPaths");
			if (paths != null && paths.size() > 0) {
				// imaLayout.removeAllViews();
				uploadPaths.addAll(paths);
				// 利用HashSet过滤掉一样的路径
				HashSet<String> set = new HashSet<String>(uploadPaths);
				uploadPaths.clear();
				uploadPaths.addAll(set);
				if (uploadPaths.size() > 9) {
					uploadPaths.removeAll(paths);
					ToastUtil.ShowToast(context, "您最多可以选择9张图片！");
					return;
				}
				setAdapter();
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	/**
	 * 调用相机拍照
	 */
	private void startPaizhao() {
		// 执行拍照前，应该先判断SD卡是否存在
		String SDState = Environment.getExternalStorageState();
		if (SDState.equals(Environment.MEDIA_MOUNTED)) {
			Intent intent = new Intent(
					android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
			/**
			 * 需要说明一下，以下操作使用照相机拍照，拍照后的图片会存放在相册中的 这里使用的这种方式有一个好处就是获取的图片是拍照后的原图
			 * 如果不实用ContentValues存放照片路径的话，拍照后获取的图片为缩略图不清晰
			 */
			// --------------------------------------------------------//
			String picName = getPhotoFileName();// 拍照后保存的图片名

			picPath = Environment.getExternalStorageDirectory()
					+ "/DCIM/Camera/" + picName;// 保存图片的路径
			File mPhotoFile = new File(picPath);// File
			if (!mPhotoFile.exists()) {
				try {
					mPhotoFile.createNewFile();
				} catch (IOException e) {
					Log.d("", e.getMessage());
					e.printStackTrace();
				}
			}
			intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mPhotoFile));

			startActivityForResult(intent, 110);
		} else {
			ToastUtil.ShowToast(context, "内存卡不存在！");
		}
	}

	/**
	 * 调用相册选取照片
	 */
	private void startXiangce() {
		Intent intent = new Intent(context, PicSelectActivity.class);
		intent.putExtra("picPathSize", uploadPaths.size());
		startActivityForResult(intent, 103);
	}

	/**
	 * 用时间戳生成照片名称
	 * 
	 * @return
	 */
	private String getPhotoFileName() {
		Date date = new Date(System.currentTimeMillis());
		SimpleDateFormat dateFormat = new SimpleDateFormat(
				"'IMG'yyyyMMddHHmmss");
		return dateFormat.format(date) + ".jpg";
	}

}
